    <template>
        <div class="boxs">
            <el-card>
                <el-form :model="queryParams" ref="queryForm" :inline="true">
                    <el-form-item label="uuid" prop="name">
                        <el-input v-model="queryParams.uuid" placeholder="uuid" />
                    </el-form-item>
                    <el-form-item label="时间范围">
                        <el-date-picker v-model="value1" value-format="yyyy-MM-dd" type="daterange" range-separator="-"
                            :start-placeholder="$t('table.start')" :end-placeholder="$t('table.end')"
                            @change="timeChange">
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" icon="el-icon-search" size="small"
                            @click="handleQuery">{{ $t('table.search') }}</el-button>
                        <el-button icon="el-icon-refresh" size="small"
                            @click="resetQuery">{{ $t('table.reset') }}</el-button>
                    </el-form-item>
                </el-form>
                <el-table border :data="moreArr" style="margin-top: 15px" v-loading="loading">
                    <el-table-column label="index" align="center" width="100" type="index" />
                    <el-table-column label="uuid" align="center" prop="uuid">
                        <template slot-scope="scope">
                            <div style=" cursor: pointer;color: blue;" @click="openDialog(scope.row.uuid)">
                                {{ scope.row.uuid }}
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column label="update_date" align="center" width="180" prop="update_date">
                    </el-table-column>
                </el-table>
                <pagination v-show="total > 0" :total="total" :page.sync="queryParams.page"
                    :limit.sync="queryParams.size" @pagination="getMore" />
            </el-card>

            <el-dialog :visible.sync="dialogVisible" @close="dialogVisible = false" width="820px">
                <div class="message_content">
                    <div class="title fw700" :class="currentName == '' ? 'kong' : ''">{{ currentName }}</div>
                    <div class="content">
                        <div class="scrollbar_box" ref="scrollbar">
                            <div class="message" style="position: relative;" v-for="(item, index) in messageList"
                                :key="index">
                                <div>
                                    <div class="timeFlag flex_center" v-if="!item.flag">
                                    </div>
                                    <div class="timeFlag flex_center" style="margin-bottom: 10px;font-size: 13px"
                                        v-else>
                                        {{ formatTime(item.eventTimeMillis) }}
                                    </div>
                                    <!-- </div> -->
                                    <div class="message-item" :class="item.role == 'system' ? 'right' : 'left'">
                                        <img class="hearimg" v-if="item.role == 'system'"
                                            src="https://insdoss.freeapptools.com/iosBeauty.jpg" />
                                        <img class="hearimg" v-else src="https://insdoss.freeapptools.com/moren.jpg" />
                                        <!-- contentType = 1 文本 -->
                                        <div class="contentx">
                                            {{ item.content }}
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </el-dialog>
            <el-dialog title="result" :visible.sync="dialogVisible1" width="800px">
                <div>
                    <v-md-preview :text="messageRes"></v-md-preview>
                </div>
            </el-dialog>
        </div>
    </template>
<script>
import { getApplicationList, restoreUserSubscriptionStatus, deleteHandel } from "@/api/SubscriptionRevive";
import { getUserList, getChatList } from "@/api/beauty";


import pk from "@/utils/pk";
import { Loading } from 'element-ui'; // 确保引入 Loading 服务
export default {
    name: "RequestRecord",
    data() {
        return {
            messageList: [

            ],
            currentName: '',
            currentImageUrl: '',
            queryParams: {
                page: 1,
                size: 10,
                dateRange: {
                    start: "",
                    end: "",
                },
                uuid: ''
            },
            stateList: [
                {
                    id: 'face',
                    name: 'face'
                },
                {
                    id: 'makeup',
                    name: 'makeup'
                },
                {
                    id: 'product',
                    name: 'product'
                },
            ],
            productIdList: [
                {
                    name: 'subs.week',
                    id: 'subs.week'
                },
                {
                    name: 'subs.week.premium',
                    id: 'subs.week.premium'
                },
                {
                    name: 'subs.month',
                    id: 'subs.month'
                },
                {
                    name: 'subs.month.premium',
                    id: 'subs.month.premium'
                },
                {
                    name: 'subs.year',
                    id: 'subs.year'
                },
                {
                    name: 'subs.year.premium',
                    id: 'subs.year.premium'
                },
                {
                    name: 'pro.lifetime',
                    id: 'pro.lifetime'
                },
                {
                    name: 'NA',
                    id: 'NA'
                },
            ],
            total: 0,
            loading: false,
            addLoading: false,
            moreArr: [],
            dialogVisible: false,
            dialogVisible1: false,

            messageRes: '',
            form: {
                description: "",
                file: "",
            },
            search: "",
            rules: {
                token: [
                    { required: true, message: "Please enter token", trigger: "blur" },
                ],
                productId: [{ required: true, message: "Please enter productId", trigger: "change" }],
            },
            value1: "",
        };
    },
    watch: {
        'form.state'(newVal) {
            if (newVal === '2') {
                this.form.productId = 'NA'; // Set to NA ID
            }
        }
    },
    created() {
        this.getMore();
        // this.init()
    },
    methods: {
        openDialogs(content) {
            this.messageRes = content
            this.dialogVisible1 = true
        },

        copyOrder() {
            const input = document.createElement('textarea');
            input.value = this.form.orderId;
            document.body.appendChild(input);
            input.select();
            try {
                document.execCommand('copy');
                this.$message({
                    message: 'Text copied to clipboard!',
                    type: 'success'
                });
            } catch (err) {
                this.$message({
                    message: 'Failed to copy text.',
                    type: 'error'
                });
            }
            document.body.removeChild(input);

        },
        copyOrder1(data1) {
            let data = this.extractErrorFromJsonString(data1)
            const input = document.createElement('textarea');
            input.value = data;
            document.body.appendChild(input);
            input.select();
            try {
                document.execCommand('copy');
                this.$message({
                    message: 'Text copied to clipboard!',
                    type: 'success'
                });
            } catch (err) {
                this.$message({
                    message: 'Failed to copy text.',
                    type: 'error'
                });
            }
            document.body.removeChild(input);
        },
        extractErrorFromJsonString(jsonString) {
            if (JSON.parse(jsonString).content && JSON.parse(jsonString).content.includes('```json')) {
                if (JSON.parse(jsonString).content.charAt(0) === '`') {
                    if (JSON.parse(JSON.parse(jsonString).content.replace(/```json|```/g, '').trim()).error) {
                        return JSON.parse(JSON.parse(jsonString).content.replace(/```json|```/g, '').trim()).error
                    } else {
                        return jsonString
                    }
                } else {
                    return JSON.parse(jsonString).content

                }

            } else {

                return JSON.parse(jsonString).refusal || JSON.parse(jsonString).content
            }
        },
        copyEmail() {
            const input = document.createElement('textarea');
            input.value = this.form.email;
            document.body.appendChild(input);
            input.select();
            try {
                document.execCommand('copy');
                this.$message({
                    message: 'Text copied to clipboard!',
                    type: 'success'
                });
            } catch (err) {
                this.$message({
                    message: 'Failed to copy text.',
                    type: 'error'
                });
            }
            document.body.removeChild(input);

        },
        copyEmail1(data) {
            const input = document.createElement('textarea');
            input.value = data;
            document.body.appendChild(input);
            input.select();
            try {
                document.execCommand('copy');
                this.$message({
                    message: 'Text copied to clipboard!',
                    type: 'success'
                });
            } catch (err) {
                this.$message({
                    message: 'Failed to copy text.',
                    type: 'error'
                });
            }
            document.body.removeChild(input);
        },
        uploadHandel(e) {
            this.form.file = e.file;
        },
        remeveFile() {
            this.form.file = "";
        },
        timeChange() {
            this.queryParams.dateRange.start = this.value1[0];
            this.queryParams.dateRange.end = this.value1[1];
            this.handleQuery();
        },
        getKeyByValue(object, value) {
            return Object.keys(object).find((key) => object[key] === value);
        },
        async getMore() {
            this.loading = true;
            let { data, total } = await getUserList(this.queryParams);
            this.loading = false;
            this.moreArr = data;
            this.total = total;
        },

        handleQuery() {
            this.queryParams.page = 1;
            this.getMore();
        },
        async affirm() {
            this.$refs["ruleForm"].validate(async (valid) => {
                if (!valid) return;
                try {
                    this.addLoading = true;
                    await restoreUserSubscriptionStatus(this.form);
                    this.addLoading = false;
                    this.$message.success("操作成功");
                    this.getMore();
                    this.dialogVisible = false;
                } catch (e) {
                    this.addLoading = false;
                }
            });
        },
        async openDialog(uuid) {
            // 开启加载动画
            const loadingInstance = Loading.service({
                lock: true,
                text: 'loading...', // 可以自定义加载文字
                spinner: 'el-icon-loading', // 使用默认的加载图标
                background: 'rgba(0, 0, 0, 0.7)' // 背景颜色，可根据需要自定义
            });

            try {
                let { data } = await getChatList({ uuid: uuid });

                data.forEach((x, i) => {
                    x.flag = true;
                    if (i - 1 >= 0) {
                        if ((Number(data[i].eventTimeMillis) - Number(data[i - 1].eventTimeMillis)) < 120000) {
                            data[i].flag = false;
                        }
                    }
                });

                this.messageList = data;
                this.currentName = '用户' + data[0].uuid;
                this.dialogVisible = true;

                setTimeout(() => {
                    this.smoothScrollToBottom();
                }, 100);

            } catch (error) {
                console.error('Error fetching chat list:', error);
            } finally {
                // 无论成功还是失败都要关闭加载动画
                loadingInstance.close();
            }
        },
        smoothScrollToBottom() {
            this.$nextTick(() => {
                const scrollbar = this.$refs.scrollbar;
                if (scrollbar) {
                    const start = scrollbar.scrollTop;
                    const end = scrollbar.scrollHeight;
                    const duration = 500; // 滑动持续时间（毫秒）
                    const startTime = performance.now();

                    const animateScroll = (currentTime) => {
                        const timeElapsed = currentTime - startTime;
                        const progress = Math.min(timeElapsed / duration, 1);
                        scrollbar.scrollTop = start + (end - start) * progress;
                        if (timeElapsed < duration) {
                            requestAnimationFrame(animateScroll);
                        }
                    };

                    requestAnimationFrame(animateScroll);
                }
            });
        },
        handleEdit(i, row) {
            if (row.images) {
                row.imagesList = row.images.split('|')
            }
            if (row.state == '0') {
                row.state = '1'
            }
            this.form = Object.assign({}, row);
            if (this.$refs.upload) {
                this.$refs.upload.clearFiles(); // 清除文件列表
            }
            this.dialogVisible = true;
        },
        handleDelete(index, row) {
            this.$confirm(this.$t('review.deleteText1'), this.$t('review.deleteText2'), {
                confirmButtonText: this.$t('review.confirm'),
                cancelButtonText: this.$t('review.close'),
                type: "error",
            }).then(async () => {
                await deleteHandel({ id: row.id });
                this.getMore();
                this.$message({
                    message: "success!",
                    type: "success",
                });
            });
        },
        resetQuery() {
            this.queryParams.uuid = null;
            this.queryParams.package_name = null;
            this.queryParams.dateRange.start = null;
            this.queryParams.dateRange.end = null;
            this.queryParams.page = 1;
            this.value1 = "";
            this.getMore();
        },

        formatTime(timestamp) {
            const now = new Date();
            const time = new Date(Number(timestamp));
            const diffMilliseconds = now - time;
            const diffSeconds = Math.floor(diffMilliseconds / 1000);
            const diffMinutes = Math.floor(diffSeconds / 60);
            const diffHours = Math.floor(diffMinutes / 60);
            const diffDays = Math.floor(diffHours / 24);

            // 获取年月日进行比较
            const isSameYear = now.getFullYear() === time.getFullYear();
            const isSameMonth = now.getMonth() === time.getMonth();
            const isSameDay = now.getDate() === time.getDate();

            if (isSameDay) {
                if (diffMinutes < 1) {
                    return '刚刚';
                }
                if (diffMinutes < 60) {
                    return `${diffMinutes}分钟前`;
                }
                return `${diffHours}小时前`;
            }

            const yesterday = new Date(now);
            yesterday.setDate(now.getDate() - 1);
            const isYesterday = time.getFullYear() === yesterday.getFullYear() &&
                time.getMonth() === yesterday.getMonth() &&
                time.getDate() === yesterday.getDate();

            if (isYesterday) {
                return `昨天 ${time.getHours().toString().padStart(2, '0')}:${time.getMinutes().toString().padStart(2, '0')}`;
            }

            if (diffDays < 7) {
                return `${diffDays}天前`;
            }

            if (isSameYear) {
                return `${time.getMonth() + 1}月${time.getDate()}日 ${time.getHours().toString().padStart(2, '0')}:${time.getMinutes().toString().padStart(2, '0')}`;
            }

            return `${time.getFullYear()}年${time.getMonth() + 1}月${time.getDate()}日 ${time.getHours().toString().padStart(2, '0')}:${time.getMinutes().toString().padStart(2, '0')}`;
        },
        formatTimestamp(timestamp) {
            const date = new Date(Number(timestamp));
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            const seconds = String(date.getSeconds()).padStart(2, '0');

            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        }
    },
};




// console.log(formatTimestamp(1735358357197));  


</script>
<style lang="scss" scoped>
.boxs {
    padding: 20px;
}

::v-deep .el-dialog__body {
    padding-top: 0;
}

::v-deep.el-input.is-disabled .el-input__inner {
    color: #333 !important;
}

::v-deep.el-textarea.is-disabled .el-textarea__inner {
    color: #333 !important;
}

::v-deep .el-upload {
    width: 100% !important;
}

::v-deep .el-upload-dragger {
    width: 100% !important;
}

.message_content {
    flex: 1;
    height: 100%;

    .title {
        font-family: PingFang SC;
        border-bottom: 1px solid #f6f6f6;
        padding: 10px;
        padding-bottom: 15px;
        margin: 0;
        color: #333;
    }


    .content {
        color: #000;
        height: 95%;
        width: 100%;

        .scrollbar_box {
            flex: 1;
            overflow-y: scroll;
            height: 700px;

            .message {
                padding: 10px 20px;
            }

            .message-item {
                display: flex;
                justify-content: flex-start;
                align-items: flex-start;
                align-content: flex-start;
                flex-wrap: nowrap;
                flex-direction: row;
                position: relative;

                .hearimg {
                    width: 45px;
                    height: 45px;
                    border-radius: 50%;
                }

                .contentx {
                    padding: 10px;
                    max-width: 500px;
                    border-radius: 10px;
                    font-size: 15px;
                    color: #000;
                    background-color: #95EC69;
                }



                .contentType3::after {
                    border: none !important;
                    display: none !important;
                }

                .content-type-right {
                    flex-direction: row-reverse;
                }

                &.right {
                    flex-direction: row-reverse;
                    color: #ffffff;

                    .hearimg {
                        margin-left: 14px;
                    }

                    .content {
                        background: var(--el-menu-active-color);
                        border-radius: 10px 0px 10px 10px;
                        // background-color: #FF0000;
                        // margin-right: 14px;
                        word-break: break-all;
                        line-height: 26px;
                        padding: 10px;
                    }
                }

                &.left {
                    .hearimg {
                        margin-right: 14px;
                    }

                    .content {
                        background: var(--el-menu-active-color);
                        border-radius: 0px 10px 10px 10px;
                        // margin-left: 14px;
                        word-break: break-all;
                        line-height: 26px;
                        padding: 8px;
                    }

                    .contentType3 {
                        margin: 0;
                        padding: 0;
                    }
                }
            }
        }

        .scrollbar_box::-webkit-scrollbar {
            display: none;
        }

        .send_box {
            position: relative;
            padding: 10px;
            height: 30%;
            border-top: 1px solid #f6f6f6;
            box-sizing: border-box;

            .drawer {
                margin-left: 30px;
                padding: 4px 10px;
                background-color: var(--el-menu-active-color);
                color: #fff;
                font-size: 12px;
                border-radius: 4px;
            }

            .send_btn {
                position: absolute;
                bottom: 20px;
                right: 10px;
                width: 70px;
                height: 35px;
                background-color: var(--el-menu-active-color);
                color: #fff;
                font-size: 15px;
                line-height: 35px;
                text-align: center;
                border-radius: 4px;
            }
        }
    }
}
</style>